#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

typedef long long ll;
typedef double db;
typedef vector < int > vec;
typedef pair < int , int > pii;

int read() {
    int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-',ch = getchar();
    while(isdigit(ch)) x = x * 10 + (ch ^ 48),ch = getchar(); return f ? -x : x;
}

const int N = 1e5 + 10;

int a[N], c[N], n, mx[N], tmx[N];
int vis[N];
ll ans;

int main() {
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
#endif
	n = in; rep(i, 1, n) a[i] = in, c[i] = in, ans += c[i];
	rep(i, 1, n)
		if(!vis[i]) {
			int x = i; while(!vis[x]) vis[x] = i, x = a[x];
			int cnt = 0;
			if(vis[x] == i) {
				while(~vis[x]) {
					cnt++; vis[x] = -1; x = a[x];
				}
			}
			if(cnt == n) return puts("0"), 0;
		}
	rep(i, 1, n) {
		mx[a[i]] = max(mx[a[i]], c[i]);
		if(vis[i] != -1) tmx[a[i]] = max(tmx[a[i]], c[i]);
	}
	rep(i, 1, n) ans -= mx[i];
	rep(i, 1, n)
		if(vis[i] == -1) {
			int x = i, res = 1e9;
			while(vis[x]) vis[x] = 0, res = min(res, mx[x] - tmx[x]), x = a[x];
			ans += res;
		}
	printf("%lld\n", ans); return 0;
}
